package com.base.library.widget;

import android.content.Context;
import android.os.Parcelable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

import com.bumptech.glide.Glide;
import com.base.library.R;
import com.base.library.adapter.MultiTypeAdapter;
import com.base.library.adapter.item.ErrorItem;
import com.base.library.adapter.item.FooterItem;
import com.base.library.adapter.item.HeaderItem;

import java.util.List;

public class RecyclerViewBase extends SwipeRefreshLoading {
    // 网络错误
    public static final int ERROR = 0;
    // 请求返回为空
    public static final int EMPTY = 1;
    // 没有更多数据了，即最后一页
    public static final int LAST = 2;
    // 正常结果
    public static final int NORMAL = 3;

    // 列表
    private RecyclerView recyclerView;
    // 加载进度条
    private ProgressBar progressBar;
    // 适配器
    private MultiTypeAdapter adapter;
    // header
    private HeaderItem headerItem;
    // error and empty
    private ErrorItem errorItem;
    // footer
    private FooterItem footerItem;

    // 是否允许下拉刷新
    private boolean pullRefresh;
    // 刷新状态
    private boolean refreshing;
    // 加载状态
    private boolean loading;
    // 是否含有header
    private boolean hasHeader;
    // 是否含有footer
    private boolean hasFooter;
    // 是否含有error
    private boolean hasError;

    public RecyclerViewBase(Context context) {
        super(context);
        init(context);
    }

    public RecyclerViewBase(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        try {
            super.onRestoreInstanceState(state);
        } catch (Exception e) {
        }
        state = null;
    }

    /**
     * 初始化
     */
    private void init(final Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.multitype_adapter_content, null);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        this.addView(view);

        recyclerView.setVisibility(GONE);
        progressBar.setVisibility(VISIBLE);

        initAdapter();
        initStateItem();
        // RecyclerView保持固定的大小,提高性能
        recyclerView.setHasFixedSize(true);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(layoutManager);
        // 滚动加载更多
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        Glide.with(context).pauseRequests();
                        break;
                    case RecyclerView.SCROLL_STATE_IDLE:
                        Glide.with(context).resumeRequests();
                        break;
                }
                if (newState == RecyclerView.SCROLL_STATE_IDLE && layoutManager.findLastVisibleItemPosition() >= adapter.getItemCount() - 1) {
                    loadMoreData();
                }
            }
        });
        recyclerView.setAdapter(adapter);

        // 设置下拉刷新
        setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });
        // 默认禁止下拉刷新
        setEnabled(pullRefresh);
    }

    public void setClipToPadding(boolean b) {
        if (recyclerView != null) {
            recyclerView.setClipToPadding(b);
        }
    }

    public void setClipChildren(boolean b) {
        if (recyclerView != null) {
            recyclerView.setClipChildren(b);
        }
    }

    public void setPaddingTop(int top) {
        if (recyclerView != null) {
            recyclerView.setPadding(0, top, 0, 0);
        }
    }

    public void setLayoutManager(RecyclerView.LayoutManager layout) {
        if (recyclerView != null && layout != null) {
            recyclerView.setLayoutManager(layout);
        }
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        adapter = new MultiTypeAdapter();
        adapter.setOnItemClickListener(new MultiTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (eventListener != null) {
                    // 内容产生错误时无法点击内容item，可以点击header item
                    if (!hasError) {
                        eventListener.onItemClick(position);
                    } else if (hasHeader && position == 0) {
                        eventListener.onItemClick(position);
                    }
                }
            }
        });
    }

    /**
     * 初始化状态item
     */
    private void initStateItem() {
        footerItem = new FooterItem();
        errorItem = new ErrorItem();

        // footer点击加载数据
        footerItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadMoreData();
            }
        });

        // error点击刷新数据
        errorItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                refreshData();
            }
        });
    }

    /**
     * 添加状态item和数据item
     * 有三种情况：网络错误，数据为空，正常结果。
     *
     * @param resultType
     * @param loadMore
     * @param datas
     */
    public void addItems(int resultType, boolean loadMore, List<MultiTypeAdapter.IItem> datas) {
        if (!loadMore) {
            adapter.clearItems();
            if (hasHeader) {
                adapter.addItem(headerItem);
            }
        }
        if (resultType == ERROR) {
            Log.d("RecyclerViewBase", "ERROR");
            if (loadMore) {
                adapter.addItem(footerItem.setState(FooterItem.ERROR));
            } else {
                hasError = true;
                adapter.addItem(errorItem.setState(ErrorItem.ERROR));
            }
        } else if (resultType == EMPTY) {
            Log.d("RecyclerViewBase", "EMPTY");
            if (loadMore) {
                adapter.addItem(footerItem.setState(FooterItem.NO_MORE));
            } else {
                hasError = true;
                adapter.addItem(errorItem.setState(ErrorItem.EMPTY));
            }
        } else if (resultType == LAST) {
            Log.d("RecyclerViewBase", "LAST");
            if (hasError) {
                adapter.removeItem(errorItem);
            }
            hasError = false;
            addDataItems(datas);
            if (hasFooter) {
                adapter.addItem(footerItem.setState(FooterItem.NO_MORE));
            }
        } else if (resultType == NORMAL) {
            Log.d("RecyclerViewBase", "NORMAL");
            if (hasError) {
                adapter.removeItem(errorItem);
            }
            hasError = false;
            addDataItems(datas);
            if (hasFooter) {
                adapter.addItem(footerItem.setState(FooterItem.LOADING));
            }
        }

        if (loadMore) {
            loadMoreDataOver();
        } else {
            refreshDataOver();
        }
    }

    /**
     * add normal
     *
     * @param loadMore 刷新方向，是上拉还是下拉
     * @param datas
     */
    public void addNormal(boolean loadMore, List<MultiTypeAdapter.IItem> datas) {
        addItems(NORMAL, loadMore, datas);
    }

    /**
     * add error
     *
     * @param loadMore
     */
    public void addError(boolean loadMore) {
        addItems(ERROR, loadMore, null);
    }

    /**
     * add empty
     *
     * @param loadMore
     */
    public void addEmpty(boolean loadMore) {
        addItems(EMPTY, loadMore, null);
    }

    /**
     * 添加数据item
     *
     * @param datas
     */
    private void addDataItems(List<MultiTypeAdapter.IItem> datas) {
        adapter.addItems(datas);
    }

    /**
     * 添加指定position上的item
     *
     * @param position
     * @param item
     */
    public void addItem(int position, MultiTypeAdapter.IItem item) {
        if (hasError) {
            adapter.removeItem(errorItem);
        }
        hasError = false;
        showRecyclerView();
        adapter.addItem(item, position);
        adapter.notifyItemChanged(Math.max(0, position - 1));
    }

    public void addItem(MultiTypeAdapter.IItem item) {
        addItem(adapter.getItemCount(), item);
    }

    /**
     * 刷新指定position上的item
     *
     * @param position
     * @param item
     */
    public void refreshItem(int position, MultiTypeAdapter.IItem item) {
        adapter.setItem(item, position);
        adapter.notifyItemChanged(position);
    }

    /**
     * 移除指定position上的item
     *
     * @param position
     */
    public void removeItem(int position) {
        adapter.removeItem(position);
        adapter.notifyItemRemoved(position);
    }

    /**
     * 加载数据
     */
    private void loadMoreData() {
        int footerPos = adapter.findPos(footerItem);
        if (!refreshing && !loading && footerPos >= 0 && !footerItem.isNoMore()) {
            Log.d("RecyclerViewBase", "loadMoreData");
            if (!footerItem.isLoading()) {
                footerItem.setState(FooterItem.LOADING);
                adapter.notifyItemChanged(footerPos);
            }
            loading = true;
            // 加载数据的时候禁止下拉刷新
            setEnabled(false);
            if (eventListener != null) {
                eventListener.onLoadMoreData();
            }
        }
    }

    /**
     * 加载数据结束
     */
    private void loadMoreDataOver() {
        Log.d("RecyclerViewBase", "loadMoreData");
        loading = false;
        // 加载数据结束的时候恢复下拉刷新
        setEnabled(pullRefresh);
        adapter.removeItem(footerItem);
        adapter.notifyDataSetChanged();
        showRecyclerView();
    }

    /**
     * 刷新数据
     */
    private void refreshData() {
        if (!loading && !refreshing) {
            setRefreshState(true);
            if (eventListener != null) {
                eventListener.onRefreshData();
            }
        }
    }

    /**
     * 刷新数据结束
     */
    private void refreshDataOver() {
        setRefreshState(false);
        adapter.notifyDataSetChanged();
        showRecyclerView();
    }

    /**
     * 显示列表隐藏进度条
     */
    private void showRecyclerView() {
        recyclerView.setVisibility(VISIBLE);
        progressBar.setVisibility(GONE);
    }

    /**
     * 显示进度条隐藏列表
     */
    public void showLoading() {
        recyclerView.setVisibility(GONE);
        progressBar.setVisibility(VISIBLE);
    }

    /**
     * 设置当前刷新状态
     *
     * @param refreshState
     */
    private void setRefreshState(boolean refreshState) {
        refreshing = refreshState;
        if (pullRefresh) {
            setRefreshing(refreshState);
        }
    }

    /**
     * 设置是否开启下拉刷新
     *
     * @param pullRefresh
     */
    public void setPullRefresh(boolean pullRefresh) {
        this.pullRefresh = pullRefresh;
        setEnabled(pullRefresh);
    }

    /**
     * 设置header item
     *
     * @param headerItem
     */
    public void setHeaderItem(HeaderItem headerItem) {
        Log.d("RecyclerViewBase", "setHeaderItem");
        this.headerItem = headerItem;
        hasHeader = true;
//        recyclerView.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
//        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) recyclerView.getLayoutParams();
//        lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    }

    /**
     * 设置error item
     *
     * @param errorItem
     */
    public void setErrorItem(ErrorItem errorItem) {
        this.errorItem = errorItem;
        errorItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                refreshData();
            }
        });

    }

    public RecyclerView getRecyclerView() {
        return recyclerView;
    }

    public MultiTypeAdapter getAdapter() {
        return adapter;
    }

    /**
     * 设置RecyclerView分隔线
     *
     * @param itemDecoration
     */
    public void setItemDecoration(DividerItemDecoration itemDecoration) {
        recyclerView.addItemDecoration(itemDecoration);
    }

    /**
     * 设置是否含有footer
     *
     * @param hasFooter
     */
    public void setHasFooter(boolean hasFooter) {
        this.hasFooter = hasFooter;
    }

    public interface RecyclerViewEventListener {
        /**
         * 加载数据
         */
        void onLoadMoreData();

        /**
         * 刷新数据
         */
        void onRefreshData();

        /**
         * item点击
         *
         * @param position
         */
        void onItemClick(int position);
    }

    private RecyclerViewEventListener eventListener;

    public void setEventListener(RecyclerViewEventListener eventListener) {
        this.eventListener = eventListener;
    }
}